function hasval(val: any): boolean{
    return val != undefined && val != null;
}

function okstr(val: string|null|undefined): boolean{
    return hasval(val) && val.trimEnd().trimStart().length>0;
}

//查找文档中第一个名称为element_name的元素
function find_first(element_name: string): HTMLOrSVGElement{
    var controls = document.getElementsByName(element_name);
    if(controls.length>0){
        return controls[0];
    }
    return null;
}

//检查输入框的值，element_name：输入框元素的name，title：输入框的标题
function check_input(element_name: string, title: string): boolean{
    let input = find_first(element_name) as HTMLInputElement;
    if(input){
        if(input.value.trim()==""){
            alert(title+'的值不能为空');
            input.focus();
            return
        }else{
            return true;
        }
    }else{
        alert(`找不到${element_name}元素`)
        return false;
    }
}

//字符串比较函数
export function cmpstr(str1: string, str2: string): number{
    if(str1>str2){
        return 1
    }else{
        if(str1<str2){
            return -1
        }else{
            return 0
        }
    }
}

//是否是时间格式
export function is_time_str(str: string): boolean{
    if(!okstr(str)){
        return false
    }
    const timePattern = /^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$/;
    if (!timePattern.test(str)) {
        return false;
    }
    return true;
}

//格式化日期和时间yyyy-mm-dd hh-nn-ss
export function fmt_time(date: Date, fmt: string):string{
    const year = date.getFullYear().toString();
    const month = (date.getMonth() + 1).toString();
    const day = date.getDate().toString();
    const hours = date.getHours().toString();
    const minutes = date.getMinutes().toString();
    const seconds = date.getSeconds().toString();
  
    return fmt.toLowerCase()
      .replace('yyyy', year)
      .replace('mm', month.padStart(2, '0'))
      .replace('dd', day.padStart(2, '0'))
      .replace('hh', hours.padStart(2, '0'))
      .replace('nn', minutes.padStart(2, '0'))
      .replace('ss', seconds.padStart(2, '0'))
      .replace('yy', year.slice(-2))
      .replace('m', month)
      .replace('d', day)
      .replace('h', hours)
      .replace('n', minutes)
      .replace('s', seconds);
}

export function now_str(fmt: string="yyyy-mm-dd hh:nn:ss"){
    return fmt_time(new Date(), fmt);
}

export {hasval, okstr, find_first, check_input}